import React, {Component} from 'react';
import * as routerRedux from "react-router-redux";
import {connect} from 'dva';
import {
  Form,
  Card,
  Select,
  List,
  Tag,
  Icon,
  Avatar,
  Row,
  Popconfirm,
  Input,
  Button,
  Dropdown,
  Menu,
  Pagination,
  Col, DatePicker
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment/moment';
import styles from './List.less';

const FormItem = Form.Item;
export default @connect(({article, loading}) => ({
  article,
  loading: loading.effects['article/fetch'],
}))

@Form.create()
class SearchList extends Component {
  state = {
    // searchValues: {},
  /*  pageData: {
      size: 10,
      page: 1
    },*/
    searchValues:this.props.article.searchValues,
    pageData:this.props.article.pageData,
    sortData: {
      order: "createTime",
      direction: "asc"
    }
  }

  componentDidMount() {
    console.log("article===>componentDidMount")
    const {dispatch} = this.props;
    dispatch({
      type: 'article/fetchCategory',
      payload: {type: 'article'},
    });
    this.fetchMore(this.state.pageData.page,this.state.pageData.size);
    dispatch({
      type: 'article/queryCount',
    });
  }

  fetchMore = (page,size) => {
    const {dispatch} = this.props;
    const {searchValues, sortData} = this.state;
    dispatch({
      type: 'article/fetch',
      payload: {start: (page - 1) * 10, size: size,searchValues:searchValues, ...searchValues, ...sortData},
    });
  };
  /*详情*/
  gotoDetail = (id) => {
    this.props.dispatch(routerRedux.push({
      pathname: `/article/detail/${id}`,
    }))
  }
  /*删除*/
  articleDelete = (id) => {
    this.props.dispatch({
      type: 'article/delete',
      payload: {
        id: id,
        state: status,
        searchValues: this.state.searchValues,
        sortData: this.state.sortData,
        pageData: {start: (this.state.pageData.page - 1) * 10, size: this.state.pageData.size}
      },
    })
  }
  /*编辑*/
  articleEdit = (id) => {
    this.props.dispatch(routerRedux.push({
      pathname: `/article/edit/${id}`,
    }))
  }
  /*编辑*/
  changeStatus = (id, status, index) => {
    this.props.dispatch({
      type: 'article/changeArticleState',
      payload: {
        id: id,
        state: status,
        searchValues: this.state.searchValues,
        sortData: this.state.sortData,
        pageData: {start: (this.state.pageData.page - 1) * 10, size: this.state.pageData.size}
      },
    })
  }
  /*
  * 分页SizeChange
  * */
  onShowSizeChange = (current, pageSize) => {
    this.setState({
      pageData: {size:pageSize,page:1}
    })
    this.fetchMore(1,pageSize);
  }
  /*pageChange*/
  changePage = (page, pageSize) => {
    this.setState({
      pageData: {size:this.state.pageData.size,page:page}
    })
    this.fetchMore(page,this.state.pageData.size);
  }
  /*重置表单*/
  handleFormReset = () => {
    const {form, dispatch} = this.props;
    form.resetFields();
    this.setState({
      searchValues: {},
    });
    const {pageData, sortData} = this.state;
    dispatch({
      type: 'article/fetch',
      payload: {start: 0,searchValues:{},size: pageData.size, ...sortData},
    });
    dispatch({
      type: 'article/queryCount',
    });
  };
  /*搜索*/
  handleSearch = e => {
    e.preventDefault();
    const {form} = this.props;
    function dealObjectValue(obj){
      var param = {};
      if ( obj === null || obj === undefined || obj === "" ) return param;
      for ( var key in obj ){
        if ( obj[key] !== null && obj[key] !== undefined && obj[key] !== "" ){
          param[key] = obj[key];
        }
      }
      return param;
    };
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        startCreateTime: fieldsValue.startCreateTime && moment(fieldsValue.startCreateTime).format("YYYY-MM-DD HH:mm:ss"),
        endCreateTime: fieldsValue.endCreateTime && moment(fieldsValue.endCreateTime).format("YYYY-MM-DD HH:mm:ss"),
      };
      this.setState({
        searchValues: dealObjectValue(values),
      });
      const {dispatch} = this.props;
      const {pageData, sortData} = this.state;
      dispatch({
        type: 'article/fetch',
        payload: {start: 0,searchValues:dealObjectValue(values),size: pageData.size, ...dealObjectValue(values), ...sortData},
      });
      dispatch({
        type: 'article/queryCount',
        payload: {...dealObjectValue(values)}
      });
    });
  };

  /*
  *
  * */
  render() {
    const {form, article: {list, categoryList, countNum}, loading,} = this.props;
    const {pageData} = this.state;
    const IconText = ({type, text}) => (
      <span>
        <Icon type={type} style={{marginRight: 8}}/>
        {text}
      </span>
    );
    const {
      form: {getFieldDecorator},
    } = this.props;
    const mainSearch = (
      <Form layout="inline">
        <Row gutter={{md: 6, lg: 24, xl: 48}}>
          <Col md={6} sm={24}>
            <FormItem label="文章标题">
              {getFieldDecorator('title',{
                initialValue: this.state.searchValues.title,
              })(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem style={{width: '100%'}} md={6} sm={24} label="文章类型">
              {getFieldDecorator('category',{
                initialValue: this.state.searchValues.category,
              })(
                <Select placeholder="请选择" style={{width: "200px"}}>
                  {categoryList&&categoryList.map(category => <Select.Option value={category.name}
                                                               key={category.categoryId}>{category.name}</Select.Option>)}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="文章标签">
              {getFieldDecorator('tag',{
                initialValue: this.state.searchValues.tag,
              })(
                <Input placeholder="请输入"/>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="文章来源">
              {getFieldDecorator('source',{
                initialValue: this.state.searchValues.source,
              })(<Select style={{width: "200px"}}>
                <Select.Option value="web" key="web">web</Select.Option>
                <Select.Option value="user" key="web">user</Select.Option>
                <Select.Option value="net" key="web">net</Select.Option>
              </Select>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="文章状态">
              {getFieldDecorator('state',{
                initialValue: this.state.searchValues.state,
              })(<Select style={{width: "200px"}}>
                <Select.Option value="UN_AUDIT" key="UN_AUDIT">UN_AUDIT</Select.Option>
                <Select.Option value="NORMAL" key="NORMAL">NORMAL</Select.Option>
                <Select.Option value="AUDIT_NOT_PASS" key="AUDIT_NOT_PASS">AUDIT_NOT_PASS</Select.Option>
              </Select>)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{md: 6, lg: 24, xl: 48}}>
          <Col md={6} sm={24}>
            <FormItem label="文章作者">
              {getFieldDecorator('author',{
                initialValue: this.state.searchValues.author,
              })(
                <Input placeholder="请输入"/>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <Form.Item label="开始时间">
              {getFieldDecorator('startCreateTime',this.state.searchValues.startCreateTime&&{
                initialValue: moment(this.state.searchValues.startCreateTime, "YYYY-MM-DD HH:mm:ss"),
              })(
                <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: "200px"}} placeholder="请输入活动开始时间"/>
              )}
            </Form.Item>
          </Col>
          <Col md={6} sm={24}>
            <Form.Item label="结束时间">
              {getFieldDecorator('endCreateTime',this.state.searchValues.endCreateTime&&{
                initialValue: moment(this.state.searchValues.endCreateTime, "YYYY-MM-DD HH:mm:ss"),
              })(
                <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: "200px"}} placeholder="请输入活动开始时间"/>
              )}
            </Form.Item>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button onClick={this.handleSearch} type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
    const ListContent = ({data: {summary, updateTime, createTime, avatar, author, href,source}}) => {
      return <div className={styles.listContent}>
        <div className={styles.description}>{summary}</div>
        <div className={styles.extra}>
          <Avatar src={avatar} size="small"/>
          <a href={href}>{author}</a>
          <em>创建于：<Icon type="dashboard" style={{marginRight: 8}}/>{moment(createTime).format('YYYY-MM-DD HH:mm')}</em>
          <em>最后一次修改：<Icon type="dashboard" style={{marginRight: 8}}/>{moment(updateTime).format('YYYY-MM-DD HH:mm')}
          </em>
          <em>文章来源：<Icon type="dashboard" style={{marginRight: 8}}/>{source}</em>
        </div>
      </div>
    };

    return (
      <PageHeaderWrapper
        title="文章列表"
        content={mainSearch}
      >
        <Card
          style={{marginTop: 24}}
          bordered={false}
          bodyStyle={{padding: '8px 32px 32px 32px'}}
        >
          <List
            size="large"
            loading={loading}
            rowKey="articleId"
            itemLayout="vertical"
            // loadMore={loadMore}
            dataSource={list}
            renderItem={(item, index) => (
              <List.Item
                key={item.articleId}
                actions={[
                  <IconText type="star-o" text={item.star || "暂无"}/>,
                  <IconText type="like-o" text={item.like || "暂无"}/>,
                  <IconText type="message" text={item.commentCount}/>,
                  <a onClick={() => this.articleEdit(item.articleId)}><Icon type="edit"
                                                                            style={{marginRight: 8}}/>修改</a>,
                  <Popconfirm onConfirm={() => this.articleDelete(item.articleId)} title="确定删除该文章？"
                              icon={<Icon type="question-circle-o" style={{color: 'red'}}/>}>
                    <a><Icon type="delete" style={{marginRight: 8}}/>删除</a>
                  </Popconfirm>,
                  <Dropdown overlay={<Menu>
                    <Menu.Item key="UN_AUDIT"
                               onClick={() => this.changeStatus(item.articleId, 'UN_AUDIT', index)}>UN_AUDIT</Menu.Item>
                    <Menu.Item key="NORMAL"
                               onClick={() => this.changeStatus(item.articleId, "NORMAL", index)}>NORMAL</Menu.Item>
                    <Menu.Item key="AUDIT_NOT_PASS"
                               onClick={() => this.changeStatus(item.articleId, "AUDIT_NOT_PASS", index)}>AUDIT_NOT_PASS</Menu.Item>
                  </Menu>} trigger={['click']}>
                    <a className="ant-dropdown-link" href="#">
                      <Icon type="edit"/>{item.state} <Icon type="down"/>
                    </a>
                  </Dropdown>
                ]}
                extra={<img width={200} alt="logo" src={item.coverPic}/>}
              >
                <List.Item.Meta
                  title={
                    <a className={styles.listItemMetaTitle} onClick={() => this.gotoDetail(item.articleId)}>
                      {item.title}
                    </a>
                  }
                  description={
                    <div>
                      <span>
                         类别：
                        {item.categorys&&item.categorys.map(categorys => {
                          return (<Tag key={categorys}>{categorys}</Tag>)
                        })}
                      </span>
                      <span>
                      标签：
                        {item.tags&&item.tags.map(tag => {
                          return (<Tag key={tag}>{tag}</Tag>)
                        })}
                    </span>
                    </div>
                  }
                />
                <ListContent data={item}/>
              </List.Item>
            )}
          />
        </Card>

        <Pagination style={{"marginTop": "30px"}} showSizeChanger onChange={this.changePage}
                    onShowSizeChange={this.onShowSizeChange} defaultPageSize={pageData.size}
                    defaultCurrent={pageData.page} total={countNum}/>
      </PageHeaderWrapper>
    );
  }
}
